<template>
  <div class="edit_page">
    <el-row :gutter="10">
      <!-- 编辑区 -->
      <el-col :span="12" class="edit_part part_box">
        <el-form class="form_content" ref="form" :rules="rules" :model="itemForm" label-width="60px">
          <el-form-item label="类型" name="type" required>
            <el-select v-model="itemForm.type" placeholder="请选择">
              <el-option
                v-for="item in typeOptions"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题干" prop="question" required>
            <el-input
              type="textarea"
              :autosize="{ minRows: 2}"
              v-model="itemForm.question">
            </el-input>
          </el-form-item>
          <el-form-item label="选项A" v-if="itemForm.type == '选择'" prop="optionA">
            <el-input v-model="itemForm.optionA"></el-input>
          </el-form-item>
          <el-form-item label="选项B" v-if="itemForm.type == '选择'" prop="optionB">
            <el-input v-model="itemForm.optionB"></el-input>
          </el-form-item>
          <el-form-item label="选项C" v-if="itemForm.type == '选择'" prop="optionC">
            <el-input v-model="itemForm.optionC"></el-input>
          </el-form-item>
          <el-form-item label="选项D" v-if="itemForm.type == '选择'" prop="optionD">
            <el-input v-model="itemForm.optionD"></el-input>
          </el-form-item>
          <el-form-item label="答案" v-if="itemForm.type == '选择'">
            <el-radio-group v-model="itemForm.code">
              <el-radio :label="0">A</el-radio>
              <el-radio :label="1">B</el-radio>
              <el-radio :label="2">C</el-radio>
              <el-radio :label="3">D</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="答案" v-if="itemForm.type == '判断'" prop="judgementAnswer">
            <el-radio-group v-model="itemForm.code">
              <el-radio :label="0">正确</el-radio>
              <el-radio :label="1">错误</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="分值" prop="score">
            <el-input-number v-model="itemForm.score" :min="1"></el-input-number>
          </el-form-item>
          <el-form-item label="图片">
            <el-input v-model="itemForm.img"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" v-if="state == 'edit'" @click="submitItem">确定</el-button>
            <el-button type="primary" v-if="state == 'add'" @click="addItem">添加</el-button>
            <el-button v-if="state == 'edit'" @click="cancelEdit">取消</el-button>
            <el-button v-if="state == 'add'" @click="resetItem">重置</el-button>
            <el-input style="width: 240px; margin:0 20px" placeholder="请输入文件名" v-model="documentName">
              <template slot="append">_yzsy</template>
            </el-input>
            <el-button type="success" @click="exportTest">确认导出</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <!-- 预览区 -->
      <el-col :span="12" class="preview_part part_box">
        <slick-list
          lockToCoontainerEdges
          v-model="topicList"
        >
          <slick-item v-for="(item, index) in topicList" :key="index" :index="index" class="topicItem">
            <div class="question">
              <div class="text">{{ index+1 + '.' + item.question }}</div>
              <div class="preview_img" v-if="item.img">
                <img :src="item.img" alt="">
              </div>
              <!-- 选择题 在选项前加上ABCD. -->
              <div class="preview_options" v-if="item.type == '选择'">
                <span
                  v-for="(oitem, oindex) in options"
                  :key="oindex"
                  :class="{ green_text: item.code == oindex }"
                >
                  {{ oitem + '.' + item['option' + oitem] }}
                </span>
              </div>
              <!-- 判断题 选项设置为正确/错误 -->
              <div class="preview_options" v-if="item.type == '判断'">
                <span :class="{ green_text: item.code == 0 }">正确</span>
                <span :class="{ green_text: item.code == 1 }">错误</span>
              </div>
              <!-- 文字录入 展示一个输入框-->
              <el-input type="textarea" v-if="item.type == '文字录入'"></el-input>
            </div>
            <div class="menu">
              <el-button type="primary" icon="el-icon-edit" circle style="margin-left:10px" @click="editItem(index)"></el-button>
              <el-button type="danger" icon="el-icon-delete" circle @click="deleteItem(index)"></el-button>
            </div>
          </slick-item>
        </slick-list>
        <!-- <div v-for="(item, index) in topicList" :key="index" class="topicItem"></div> -->
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { SlickList, SlickItem } from 'vue-slicksort';
import * as XLSX from "xlsx";
// 编辑试题 导出答案加密后的文件
const defaultForm = {
  type: "选择",
  score: 1,
  code: 0
}
export default {
  components: {
    SlickList,
    SlickItem
  },
  data() {
    let validateSelect = (rule, value, callback) => {
      console.log('rule ? => ', rule);
      if (this.itemForm.type == '选择' && !value) {
        callback(new Error());
      } else {
        callback();
      }
    };
    return {
      itemForm: {}, // 正在编辑的题{type(类型),question(题干),score(分值),code(答案)}
      topicList: [], // 题目列表
      typeOptions: ['选择','判断','文字录入'], // 题目类型选项
      options: ["A", "B", "C", "D"], // 展示选择题的选项
      rules: {
        question: [{required: true}],
        optionA: [{validator: validateSelect, trigger: ['blur']}],
        optionB: [{validator: validateSelect, trigger: ['blur']}],
        optionC: [{validator: validateSelect, trigger: ['blur']}],
        optionD: [{validator: validateSelect, trigger: ['blur']}],
        // judgementAnswer: [{required: this.itemForm.type == '判断'}],
        score: [{required: true}]
      },
      state: 'add', // 状态：新增/修改
      editIndex: 0, // 正在编辑的题号
      documentName: '', // 导出文件名
    }
  },
  methods: {
    // 生成随机字符串
    generateRandomString(length) {
      const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      return Array.from({ length }).map(() => characters.charAt(Math.floor(Math.random() * characters.length))).join("");
    },
    // 处理试题，导出
    dealData() {},
    // 添加题目
    addItem() {
      console.log('开始处理添加题目 =》 ', this.itemForm)
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.topicList.push(this.itemForm);
          this.resetItem();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 重置表单
    resetItem() {
      this.itemForm = JSON.parse(JSON.stringify(defaultForm));
    },
    // 编辑列表中的题目
    editItem(i) {
      this.editIndex = i;
      this.itemForm = JSON.parse(JSON.stringify(this.topicList[i]));
      this.state = 'edit';
    },
    // 确定修改
    submitItem() {
      this.topicList.splice(this.editIndex, 1, this.itemForm);
      this.editIndex = 0;
      this.resetItem();
      this.state = 'add';
    },
    // 取消编辑
    cancelEdit() {
      this.resetItem()
      this.editIndex = 0;
      this.state = 'add';
    },
    // 删除题目
    deleteItem(i) {
      this.$confirm('删除后无法恢复, 确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.topicList.splice(i, 1);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 导出试卷
    exportTest() {
      console.log('导出 ------->', this.topicList)
      if (!this.documentName) {
        this.$message('请输入文件名')
      }else {
        const questionNumber = this.topicList.length;
        let totalScore = 0;
        this.topicList.forEach(item => {
          totalScore += item.score;
        })
        this.$confirm(`试题共${questionNumber}道题目，总分为${totalScore}`, '确认导出？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.startDeal();
        });
      }
    },
    startDeal() {
      /**
       * 处理文件，给答案加密，abcd对应0123，加密后放在第10位(在数组中下标为9)
       * 前四位固定为 "yzsy",后面加5位随机字符串，加答案对应的数字，后面加4位随机字符串
       * 例如答案为d，加密后示例：yszyh8ui3km17b
       * */
      // const dict = ["a", "b", "c", "d", "A", "B", "C", "D"];
      let pswStart,
        pswEnd,
        ans = "";
      try {
        this.topicList.forEach((item) => {
          if (!item.type) {
            // 检查文件内容中是否包含type，如果没有抛出错误。
            console.log("no error??", item.type);
            throw new Error("文件格式错误");
          }
          if (item.type == "选择" || item.type == "判断") {
            // 给选择、判读的答案加密
            ans = item.code;
            ans = ans > 3 ? ans - 4 : ans;
            if (ans < 0) throw new Error("答案有误");
            pswStart = this.generateRandomString(5);
            pswEnd = this.generateRandomString(4);
            console.log("ans => ", ans, pswStart, pswEnd);
            item.code = "yzsy" + pswStart + ans + pswEnd;
          }
        });
        console.log("deal success => ", this.topicList);
        this.exportToExcel(this.topicList, this.documentName + '_yzsy');
      } catch (error) {
        console.log("文件处理error =>", error);
        this.$message({
          message: "文件处理出错！请仔细检查文件内容，或联系吕政均。",
          type: "error",
        });
      }
      // this.exportToExcel(this.topicList, this.originName + '_yzsy')
    },
    exportToExcel(data, fileName) {
      // 导出
      // 将数据转换为工作表
      const worksheet = XLSX.utils.json_to_sheet(data);
      // 创建工作簿并添加工作表
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
      // 生成Excel文件
      const excelBuffer = XLSX.write(workbook, {
        bookType: "xlsx",
        type: "array",
      });
      // 创建Blob对象
      const dataBlob = new Blob([excelBuffer], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",
      });
      // 创建链接并模拟点击下载
      const downloadLink = document.createElement("a");
      downloadLink.href = window.URL.createObjectURL(dataBlob);
      downloadLink.download = fileName + ".xlsx";
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
    },
  },
  mounted() {
    this.resetItem();
  }
}
</script>

<style lang="less" scoped>
.edit_page {
  // height: calc(100vh - 72px);
  .name_input {
    display: inline;
    width: 120px;
  }
  .part_box {
    border: 1px solid #eee;
    border-radius: 10px;
    height: calc(100vh - 78px);
    line-height: 50px;
    padding: 10px;
    overflow: auto;
  }
  .question_label {
    text-align: right;
  }
  .preview_part {
    .topicItem {
      border-bottom: 1px solid #ccc;
      padding: 10px;
      display: flex;
      .question {
        font-size: 20px;
        flex: 1;
        .text {
          line-height: 28px;
        }
        .preview_img {
          img {
            width: 36vw;
          }
        }
      }
      .menu {
        width: 50px;
        border-left: 1px solid #ccc
      }
    }
    .green_text{
      color: #009100;
      font-weight: bold;
    }
  }
}
</style>